package com.dtease.agent.sync.extractor;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.dtease.agent.biz.agentstore.entity.BasToolsMetaDatabase;
import com.dtease.agent.biz.agentstore.service.IBasToolsMetaDatabaseService;
import com.dtease.agent.biz.resource.dto.BasStorageDTO;
import com.dtease.agent.common.utils.JdbcUtil;
import com.dtease.agent.common.utils.PasswordOperateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.text.MessageFormat;

/**
 * @description MySQL元数据提取器
 * @author chentl
 * @class MySqlMetadataExtractor
 * @package com.dtease.agent.metadata.sync
 * @since 2025/5/7 14:24
 */
@Slf4j
@Component
public class MySqlMetadataExtractor extends AbstractMetadataExtractor implements IMetadataExtractor {

    @Resource
    private IBasToolsMetaDatabaseService toolsMetaDatabaseService;

    @Override
    protected String getQuerySql(BasStorageDTO storage) {
        String dbName = JSONUtil.parseObj(storage.getParameter()).getStr("dbName");
        return "SELECT t.TABLE_NAME as tableName, t.TABLE_COMMENT as tableComment, " +
                "c.COLUMN_NAME as columnName, c.COLUMN_TYPE as columnType, c.COLUMN_COMMENT as columnComment " +
                "FROM information_schema.TABLES t " +
                "JOIN information_schema.COLUMNS c ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME " +
                "WHERE t.TABLE_SCHEMA = '" + dbName + "'";
    }

    @Override
    protected DataSource getDataSource(BasStorageDTO storage) {
        String databaseName = getDatabaseName(storage);
        JSONObject parameter = JSONUtil.parseObj(storage.getParameter());
        String connectUrl = parameter.getStr("connectUrl");
        String jdbcUrl = StringUtils.contains(connectUrl, "jdbc") ? connectUrl : MessageFormat.format("jdbc:mysql://{0}/{1}?characterEncoding=utf8&useSSL=false", connectUrl,databaseName);
        String username = parameter.getStr("userName");
        String password = PasswordOperateUtils.decrypt(parameter.getStr("password"));
        String driver = parameter.getStr("driver", "com.mysql.jdbc.Driver");
        return JdbcUtil.buildDataSource(jdbcUrl, username, password, driver);
    }


    @Override
    protected IService<BasToolsMetaDatabase> getToolsMetaDatabaseService() {
        return toolsMetaDatabaseService;
    }
}